package cn.diancan.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import cn.diancan.model.types.CommonConstant;
import cn.diancan.service.ProductService;
import org.springframework.stereotype.Component;

import cn.diancan.dao.MyBaseDao;
import cn.diancan.exception.OutMsgException;
import cn.diancan.model.Brand;
import cn.diancan.model.Goods;
import cn.diancan.model.GoodsCategory;
import cn.diancan.model.types.CommonType;
import cn.diancan.service.BrandService;
import cn.diancan.service.GoodsCategoryService;
import cn.diancan.service.GoodsService;
import cn.diancan.util.DateUtil;
import cn.diancan.vo.model.GoodsVo;
import cn.diancan.vo.other.Pager;
import cn.diancan.vo.other.ResultVoUtil;

@Component("goodsService")
public class GoodsServiceImpl implements GoodsService {


    @Resource(name = "brandService")
    private BrandService brandService;

    @Resource(name = "goodsCategoryService")
    private GoodsCategoryService goodsCategoryService;

    @Resource(name = "MyBaseDao")
    private MyBaseDao<Goods> goodsDao;


    @Override
    public boolean saveGoods(Long brandId, Long goodsCategoryId, String goodsNumber, String goodsName, String goodsDescription, String goodsBarcode) throws OutMsgException, Exception {
        if (null == brandId) {
            throw new OutMsgException("请选择品牌");
        }
        if (null == goodsCategoryId) {
            throw new OutMsgException("请选择分类");
        }
        Brand brand = brandService.findBrandById(brandId);
        if (null == brand) {
            throw new OutMsgException("请选择品牌");
        }
        GoodsCategory goodsCategory = goodsCategoryService.findGoodsCategoryById(goodsCategoryId);
        if (null == goodsCategory) {
            throw new OutMsgException("请选择分类");
        }

        Goods goods = new Goods();
        goods.setGoodsNumber(goodsNumber);
        goods.setBrandId(brandId);

        goods.setGoodsCategoryId(goodsCategoryId);

        goods.setCreateTime(DateUtil.currentDateTime());
        goods.setIsDelete(CommonType.Delete.NO);

        goods.setGoodsName(goodsName);
        goods.setGoodsDescription(goodsDescription);
        goods.setGoodsBarCode(goodsBarcode);
        goods.setTotalStockCount(0);
        goods.setLastUpdateTimeStamp(System.currentTimeMillis());
        goodsDao.save(goods);

        return true;
    }

    @Override
    public Goods saveGoods(Goods tempGoods, boolean addProduct) throws OutMsgException, Exception {
        Long brandId = tempGoods.getBrandId();
        Long goodsCategoryId = tempGoods.getGoodsCategoryId();
        String goodsNumber = tempGoods.getGoodsNumber();
        String goodsName = tempGoods.getGoodsName();
        String goodsDescription = tempGoods.getGoodsDescription();
        String goodsBarcode = tempGoods.getGoodsBarCode();

        String range = tempGoods.getRangeStr();
        Double tagPrice = tempGoods.getTagPrice(); // 吊牌价
        Double retailPrice = tempGoods.getRetailPrice(); // 销售价格
        String unit = tempGoods.getUnit();

        String year = tempGoods.getYear(); // 年份
        String season = tempGoods.getSeason(); // 季节
        Integer applySex = tempGoods.getApplySex(); // 0 女 1 男 2 全部
        Double wholeSalePrice = tempGoods.getWholeSalePrice();//
        String goodsRemark = tempGoods.getGoodsRemark();


        if (null == brandId) {
            throw new OutMsgException("请选择品牌");
        }
        if (null == goodsCategoryId) {
            throw new OutMsgException("请选择分类");
        }
        Brand brand = brandService.findBrandById(brandId);
        if (null == brand) {
            throw new OutMsgException("请选择品牌");
        }

        GoodsCategory goodsCategory = goodsCategoryService.findGoodsCategoryById(goodsCategoryId);
        if (null == goodsCategory) {
            throw new OutMsgException("请选择分类");
        }


        if (null == goodsNumber || "".equals(goodsNumber.trim())) {
            throw new OutMsgException("货品号不能为空");
        }
        goodsNumber = goodsNumber.trim();
        Goods goods = findByGoodsNumber(brandId, goodsNumber);
        if (null != goods) {
            throw new OutMsgException("该货号已存在");
        }
        if (null == goodsName || "".equals(goodsName.trim())) {
            throw new OutMsgException("产品名不能为空");
        }
        goodsName = goodsName.trim();
        if (null == retailPrice || retailPrice <= 0) {
            throw new OutMsgException("请设置价格");
        }
        if (null == tagPrice || tagPrice <= 0) {
            throw new OutMsgException("请设置价格");
        }


        goods = new Goods();
        goods.setIndexNo(10);
        goods.setGoodsNumber(goodsNumber);
        goods.setBrandId(brandId);
        goods.setGoodsCategoryId(goodsCategoryId);

        if (goodsCategory.getLevel().equals(1)) {
            goods.setFirstGoodsCategoryId(goodsCategory.getId());
            goods.setSecondGoodsCategoryId(null);
            goods.setGoodsCategoryPath("#" + goodsCategory.getId() + "#");
        } else if (goodsCategory.getLevel().equals(2)) {
            goods.setFirstGoodsCategoryId(goodsCategory.getParentId());
            goods.setSecondGoodsCategoryId(goodsCategory.getId());
            goods.setGoodsCategoryPath("#" + goodsCategory.getParentId() + "#" + goodsCategory.getId() + "#");
        }

        goods.setCreateTime(DateUtil.currentDateTime());
        goods.setIsDelete(CommonType.Delete.NO);
        goods.setGoodsName(goodsName);

        if (null == goodsDescription) {
            goodsDescription = "";
        }
        goods.setGoodsDescription(goodsDescription);
        if (null == goodsBarcode) {
            goodsBarcode = "";
        }
        goods.setGoodsBarCode(goodsBarcode);
        goods.setTotalStockCount(0);
        goods.setRangeStr(range);

        goods.setTagPrice(tagPrice);
        goods.setRetailPrice(retailPrice);

        if (null == unit) {
            unit = "";
        }
        unit = unit.trim();

        goods.setUnit(unit);
        goods.setYear(year);

        if (null == season) {
            season = "";
        }
        season = season.trim();
        goods.setSeason(season);
        goods.setApplySex(applySex);
        if (null == wholeSalePrice) {
            wholeSalePrice = 0d;
        }
        goods.setWholeSalePrice(wholeSalePrice);
        goods.setGoodsRemark(goodsRemark);
        goods.setLastUpdateTimeStamp(System.currentTimeMillis());
        goodsDao.save(goods);

        if (addProduct) {
            //添加默认 默认
            productService.saveProduct(goods.getId(), new Long[]{CommonConstant.SpecificationId}, "DE"+goods.getId(), goods.getTagPrice(), goods.getRetailPrice(), 0);
        }

        return goods;
    }


    @Override
    public Goods saveGoods2(Goods tempGoods, boolean addProduct) throws OutMsgException, Exception {
        Long brandId = tempGoods.getBrandId();
        Long goodsCategoryId = tempGoods.getGoodsCategoryId();
        String goodsNumber = tempGoods.getGoodsNumber();
        String goodsName = tempGoods.getGoodsName();
        String goodsDescription = tempGoods.getGoodsDescription();
        String goodsBarcode = tempGoods.getGoodsBarCode();

        String range = tempGoods.getRangeStr();
        Double tagPrice = tempGoods.getTagPrice(); // 吊牌价
        Double retailPrice = tempGoods.getRetailPrice(); // 销售价格
        String unit = tempGoods.getUnit();

        String year = tempGoods.getYear(); // 年份
        String season = tempGoods.getSeason(); // 季节
        Integer applySex = tempGoods.getApplySex(); // 0 女 1 男 2 全部
        Double wholeSalePrice = tempGoods.getWholeSalePrice();//
        String goodsRemark = tempGoods.getGoodsRemark();


        if (null == brandId) {
            throw new OutMsgException("请选择品牌");
        }
        if (null == goodsCategoryId) {
            throw new OutMsgException("请选择分类");
        }
        Brand brand = brandService.findBrandById(brandId);
        if (null == brand) {
            throw new OutMsgException("请选择品牌");
        }

        GoodsCategory goodsCategory = goodsCategoryService.findGoodsCategoryById(goodsCategoryId);
        if (null == goodsCategory) {
            throw new OutMsgException("请选择分类");
        }


        if (null == goodsNumber || "".equals(goodsNumber.trim())) {
            throw new OutMsgException("货品号不能为空");
        }
        goodsNumber = goodsNumber.trim();
        Goods goods = findByGoodsNumber(brandId, goodsNumber);
        if (null != goods) {
            throw new OutMsgException("该货号已存在");
        }
        if (null == goodsName || "".equals(goodsName.trim())) {
            throw new OutMsgException("产品名不能为空");
        }
        goodsName = goodsName.trim();


        goods = new Goods();
        goods.setIndexNo(10);
        goods.setGoodsNumber(goodsNumber);
        goods.setBrandId(brandId);
        goods.setGoodsCategoryId(goodsCategoryId);

        if (goodsCategory.getLevel().equals(1)) {
            goods.setFirstGoodsCategoryId(goodsCategory.getId());
            goods.setSecondGoodsCategoryId(null);
            goods.setGoodsCategoryPath("#" + goodsCategory.getId() + "#");
        } else if (goodsCategory.getLevel().equals(2)) {
            goods.setFirstGoodsCategoryId(goodsCategory.getParentId());
            goods.setSecondGoodsCategoryId(goodsCategory.getId());
            goods.setGoodsCategoryPath("#" + goodsCategory.getParentId() + "#" + goodsCategory.getId() + "#");
        }

        goods.setCreateTime(DateUtil.currentDateTime());
        goods.setIsDelete(CommonType.Delete.NO);
        goods.setGoodsName(goodsName);

        if (null == goodsDescription) {
            goodsDescription = "";
        }
        goods.setGoodsDescription(goodsDescription);
        if (null == goodsBarcode) {
            goodsBarcode = "";
        }
        goods.setGoodsBarCode(goodsBarcode);
        goods.setTotalStockCount(0);
        goods.setRangeStr(range);

        goods.setTagPrice(tagPrice);
        goods.setRetailPrice(retailPrice);

        if (null == unit) {
            unit = "";
        }
        unit = unit.trim();

        goods.setUnit(unit);
        goods.setYear(year);

        if (null == season) {
            season = "";
        }
        season = season.trim();
        goods.setSeason(season);
        goods.setApplySex(applySex);
        if (null == wholeSalePrice) {
            wholeSalePrice = 0d;
        }
        goods.setWholeSalePrice(wholeSalePrice);
        goods.setGoodsRemark(goodsRemark);
        goods.setLastUpdateTimeStamp(System.currentTimeMillis());
        goodsDao.save(goods);

        if (addProduct) {
            //添加默认 默认
            productService.saveProduct(goods.getId(), new Long[]{CommonConstant.SpecificationId}, "DE"+goods.getId(), goods.getTagPrice(), goods.getRetailPrice(), 0);
        }

        return goods;
    }

    @Resource(name = "productService")
    private ProductService productService;


    @Override
    public boolean updateGoods(Goods tempGoods) throws OutMsgException, Exception {

        Long brandId = tempGoods.getBrandId();
        Long goodsCategoryId = tempGoods.getGoodsCategoryId();
        String goodsNumber = tempGoods.getGoodsNumber();
        String goodsName = tempGoods.getGoodsName();
        String goodsDescription = tempGoods.getGoodsDescription();
        String goodsBarcode = tempGoods.getGoodsBarCode();

        String range = tempGoods.getRangeStr();
        Double tagPrice = tempGoods.getTagPrice(); // 吊牌价
        Double retailPrice = tempGoods.getRetailPrice(); // 销售价格
        String unit = tempGoods.getUnit();

        String year = tempGoods.getYear(); // 年份
        String season = tempGoods.getSeason(); // 季节
        Integer applySex = tempGoods.getApplySex(); // 0 女 1 男 2 全部
        Double wholeSalePrice = tempGoods.getWholeSalePrice();//
        String goodsRemark = tempGoods.getGoodsRemark();


        if (null == brandId) {
            throw new OutMsgException("请选择品牌");
        }
        if (null == goodsCategoryId) {
            throw new OutMsgException("请选择分类");
        }
        Brand brand = brandService.findBrandById(brandId);
        if (null == brand) {
            throw new OutMsgException("请选择品牌");
        }

        GoodsCategory goodsCategory = goodsCategoryService.findGoodsCategoryById(goodsCategoryId);
        if (null == goodsCategory) {
            throw new OutMsgException("请选择分类");
        }


        if (null == goodsNumber || "".equals(goodsNumber.trim())) {
            throw new OutMsgException("货品号不能为空");
        }

        if (null == tempGoods.getId()) {
            throw new OutMsgException("参数错误");
        }
        //这里也不一样
    /*Goods goods = findByGoodsNumber(brandId,goodsNumber);
	if(null!=goods){
	    throw new OutMsgException("该货号已存在");
	}*/
        goodsNumber = goodsNumber.trim();
        Goods goods = findByGoodsId(tempGoods.getId());
        if (null == goods) {
            throw new OutMsgException("该货号不存在");
        }
        goods.setGoodsNumber(goodsNumber);

        if (null == goodsName || "".equals(goodsName.trim())) {
            throw new OutMsgException("产品名不能为空");
        }
        goodsName = goodsName.trim();
        if (null == retailPrice || retailPrice <= 0) {
            throw new OutMsgException("请设置价格");
        }
        if (null == tagPrice || tagPrice <= 0) {
            throw new OutMsgException("请设置价格");
        }


        //货号也不能更改//这里也不一样 不能 new

        //goods = new Goods();
        //goods.setGoodsNumber(goodsNumber);
        goods.setBrandId(brandId);
        goods.setGoodsCategoryId(goodsCategoryId);

        if (goodsCategory.getLevel().equals(1)) {
            goods.setFirstGoodsCategoryId(goodsCategory.getId());
            goods.setSecondGoodsCategoryId(null);
            goods.setGoodsCategoryPath("#" + goodsCategory.getId() + "#");
        } else if (goodsCategory.getLevel().equals(2)) {
            goods.setFirstGoodsCategoryId(goodsCategory.getParentId());
            goods.setSecondGoodsCategoryId(goodsCategory.getId());
            goods.setGoodsCategoryPath("#" + goodsCategory.getParentId() + "#" + goodsCategory.getId() + "#");
        }

        goods.setCreateTime(DateUtil.currentDateTime());
        goods.setIsDelete(CommonType.Delete.NO);
        goods.setGoodsName(goodsName);

        if (null == goodsDescription) {
            goodsDescription = "";
        }
        goods.setGoodsDescription(goodsDescription);
        if (null == goodsBarcode) {
            goodsBarcode = "";
        }
        goods.setGoodsBarCode(goodsBarcode);
        //总库存不能这样更改//这里也不一样
        //goods.setTotalStockCount(0);
        goods.setRangeStr(range);

        goods.setTagPrice(tagPrice);
        goods.setRetailPrice(retailPrice);

        if (null == unit) {
            unit = "";
        }
        unit = unit.trim();

        goods.setUnit(unit);
        goods.setYear(year);

        if (null == season) {
            season = "";
        }
        season = season.trim();
        goods.setSeason(season);
        goods.setApplySex(applySex);
        if (null == wholeSalePrice) {
            wholeSalePrice = 0d;
        }
        goods.setWholeSalePrice(wholeSalePrice);
        goods.setGoodsRemark(goodsRemark);
        goods.setLastUpdateTimeStamp(System.currentTimeMillis());
        goodsDao.update(goods);

        return true;

    }


    @Override
    public Goods findByGoodsId(Long goodsId) throws OutMsgException {
        if (null == goodsId) {
            throw new OutMsgException("参数错误");
        }
        return goodsDao.get("FROM Goods WHERE id=? AND isDelete=?", new Object[]{goodsId, CommonType.Delete.NO});
    }


    @Override
    public Pager findPager(Pager pager) throws OutMsgException {
        String hql = "FROM Goods WHERE isDelete=? ";
        List<Object> param = new ArrayList<Object>();
        param.add(CommonType.Delete.NO);


        List<Goods> goods = goodsDao.find(hql, param, pager.getPageNumber(), pager.getPageSize());
        Long count = goodsDao.count("SELECT count(id) " + hql, param);
        pager.setList(goods);
        pager.setTotalCount(count.intValue());
        return pager;
    }


    @Override
    public Pager findGoodsVoPager(Pager pager) throws OutMsgException {

        String hql_s = "SELECT brandId,firstGoodsCategoryId,secondGoodsCategoryId,goodsCategoryId,goodsCategoryPath,goodsNumber,goodsName,goodsDescription,goodsBarcode,rangeStr,tagPrice,retailPrice,unit,year,season,applySex,wholeSalePrice,goodsRemark,totalStockCount";
        hql_s += ",g1.createTime,g1.id,g1.id AS goodsId,b2.brandName AS brandName,g3.categoryName AS firstGoodsCategoryName,g4.categoryName AS secondGoodsCategoryName ";
        String hql = " FROM Goods AS g1 LEFT JOIN Brand AS b2 ON g1.brandId= b2.id  ";
        hql += " LEFT JOIN GoodsCategory AS g3 ON g1.firstGoodsCategoryId=g3.id ";
        hql += " LEFT JOIN GoodsCategory AS g4 ON g1.secondGoodsCategoryId= g4.id ";

        hql += " WHERE g1.isDelete=? AND g3.isHide=? Order By g1.indexNo DESC";
        List<Object> param = new ArrayList<Object>();
        param.add(CommonType.Delete.NO);
        param.add(CommonType.Hide.NO);


        List<Object[]> objs = goodsDao.findSql(hql_s + hql, param, pager.getPageNumber(), pager.getPageSize());
        BigInteger count = (BigInteger) goodsDao.countSQL("SELECT count(g1.id) " + hql, param.toArray(new Object[]{}));

        List<GoodsVo> goods = ResultVoUtil.object2Model(GoodsVo.class, objs, hql_s + hql);
        pager.setList(goods);
        pager.setTotalCount(count.intValue());

        return pager;
    }

    @Override
    public boolean deleteGoods(Long goodsId) throws OutMsgException, Exception {


        return false;
    }


    @Override
    public Goods findByGoodsNumber(Long brandId, String goodsNumber) throws OutMsgException {
        if (null == brandId || null == goodsNumber) {
            throw new OutMsgException("货品号不能为空");
        }


        return goodsDao.get("FROM Goods WHERE isDelete=? AND goodsNumber=? AND brandId=?", new Object[]{CommonType.Delete.NO, goodsNumber, brandId});
    }

    @Override
    public String findNewGoodsNumber() {
        Goods goods = goodsDao.get("FROM Goods ORDER BY id DESC", new Object[]{});
        if (null != goods) {
            return "P" + (goods.getId() + 1);
        }
        return "P000001";
    }

    @Override
    public Long findCountGoods(Long brandId) throws OutMsgException {
        Long count = goodsDao.count("Select count(id) FROM Goods WHERE brandId=? ", new Object[]{brandId});

        return count;
    }


    @Override
    public boolean updateM() throws OutMsgException, Exception {
        Goods goods = goodsDao.get("FROM Goods WHERE goodsName like '小菜%.0' ", new Object[]{});
        if (null!=goods){
            goods.setGoodsName("小菜"+goods.getTagPrice().intValue());
            goodsDao.update(goods);
            return true;
        }


        return false;
    }

    @Override
    public boolean updateMoveGoods(Long goodsId, Integer moveType) throws OutMsgException, Exception {
        Goods goods = findByGoodsId(goodsId);
        if (null==goods){
            return false;
        }
        if(null == moveType || moveType.equals(1)){
            goods.setIndexNo(goods.getIndexNo()+1);
        }else if(moveType.equals(2)) {
            goods.setIndexNo(goods.getIndexNo()-1);
        }else if(moveType.equals(3)){
            Integer count = goodsDao.count2("Select max(indexNo) FROM Goods " );
            goods.setIndexNo(count.intValue()+1);
        }
        goodsDao.update(goods);
        return true;
    }

}
